import tkinter as tk
from tkinter import scrolledtext
import json
import tkinter.ttk as ttk
import tkinter.messagebox as messagebox

def format_json():
    try:
        input_json = input_text.get("1.0", tk.END).strip()
        data = json.loads(input_json)
        # 清空 Treeview
        for item in output_tree.get_children():
            output_tree.delete(item)
        # 递归插入 JSON 数据到 Treeview
        insert_json(data, output_tree)
        expand_all_nodes(output_tree.get_children())
    except json.JSONDecodeError:
        for item in output_tree.get_children():
            output_tree.delete(item)
        output_tree.insert("", "end", text="输入的 JSON 格式不正确，请检查。")

def insert_json(data, parent, parent_id=''):
    if isinstance(data, dict):
        # 保持 JSON 对象的格式
        for key, value in data.items():
            if isinstance(value, (dict, list)):
                node_id = output_tree.insert(parent_id, "end", text=f"{key}: ")
                insert_json(value, output_tree, node_id)
            else:
                # 直接显示键值对
                output_tree.insert(parent_id, "end", text=f"{key}: {json.dumps(value, ensure_ascii=False)}")
    elif isinstance(data, list):
        # 保持 JSON 数组的格式
        for index, value in enumerate(data):
            node_id = output_tree.insert(parent_id, "end", text=f"[{index}]: ")
            if isinstance(value, (dict, list)):
                insert_json(value, output_tree, node_id)
            else:
                # 最后一层数据直接显示
                output_tree.insert(node_id, "end", text=json.dumps(value, ensure_ascii=False))

    # 展开最后一个对象的所有节点
    if not parent_id:  # 如果是根节点
        expand_all_nodes(parent.get_children())

def expand_all_nodes(nodes):
    for node in nodes:
        output_tree.item(node, open=True)
        children = output_tree.get_children(node)
        expand_all_nodes(children)

def copy_formatted_json():
    try:
        input_json = input_text.get("1.0", tk.END).strip()
        data = json.loads(input_json)
        formatted_json = json.dumps(data, indent=4, ensure_ascii=False)
        root.clipboard_clear()
        root.clipboard_append(formatted_json)
        messagebox.showinfo("复制成功", "格式化后的 JSON 内容已复制到剪贴板。")
    except json.JSONDecodeError:
        messagebox.showerror("错误", "输入的 JSON 格式不正确，请检查。")

# 创建主窗口
root = tk.Tk()
root.title("JSON 格式化工具")

# 设置窗口初始大小
root.geometry("800x600")  # 设置窗口初始宽度为 800，高度为 600

# 允许窗口最大化和最小化
root.resizable(True, True)  # 允许在水平和垂直方向上调整窗口大小

# 创建左右框架
left_frame = tk.Frame(root)
left_frame.pack(side=tk.LEFT, fill=tk.Y)
right_frame = tk.Frame(root)
right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)

# 创建输入框
input_label = tk.Label(left_frame, text="输入 JSON:")
input_label.pack()
input_text = scrolledtext.ScrolledText(left_frame, width=40, height=20)
input_text.pack()

# 创建格式化按钮
format_button = tk.Button(left_frame, text="格式化", command=format_json)
format_button.pack()

# 创建复制按钮
copy_button = tk.Button(left_frame, text="复制格式化内容", command=copy_formatted_json)
copy_button.pack()

# 创建输出 Treeview
output_label = tk.Label(right_frame, text="格式化后的 JSON:")
output_label.pack()
output_tree = ttk.Treeview(right_frame, selectmode='browse')
output_tree.pack(fill=tk.BOTH, expand=True)

# 运行主循环
root.mainloop()